﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Windows.Forms;

namespace SP.OpenSource.CDC.Monitor
{
    public partial class CDCLogs : UserControl
    {
        String m_sConnectedConfigID = String.Empty;


        String m_sConnectionString = String.Empty;
        String m_sStateConnectionString = String.Empty;
        String m_sConnectedDBName = String.Empty;
        String m_sConnectedServerName = String.Empty;

        String m_sErrorMessage = String.Empty;
        String m_sFormTitle = "MonitorCDC - Captured Data Logs";
        String m_sGenericErrorMessage = "Exception raised while processing request." + Environment.NewLine + "Error Message: ";

        String m_sQueryErrorLog = String.Empty;
        String m_sQueryScanLog = String.Empty;

        public CDCLogs()
        {
            InitializeComponent();
        }
        public CDCLogs(String sConnectionString, String sConnectedDBName, String sConnectedServerName, String sConnectedConfigID)
        {
            InitializeComponent();

            m_sConnectedConfigID = sConnectedConfigID;
            m_sConnectionString = sConnectionString;
            m_sConnectedDBName = sConnectedDBName;
            m_sConnectedServerName = sConnectedServerName;

            m_sQueryErrorLog = "select session_id as SessionID, phase_number as PhaseNumber,";
            m_sQueryErrorLog += " entry_time as EntryTime, [error_number] as ErrorNumber, ";
            m_sQueryErrorLog += " [error_severity]  as ErrorSeverity, [error_state] as ErrorState, ";
            m_sQueryErrorLog += " [error_message] as ErrorMessage, start_lsn as StartLSN, begin_lsn as BeginLSN, sequence_value as SequenceValue ";
            m_sQueryErrorLog += " from sys.dm_cdc_errors ";
            
            m_sQueryScanLog = "SELECT top 200 start_time as StartTime, end_time as EndTime, Duration, scan_phase as ScanPhase,";
            m_sQueryScanLog += " error_count as ErrorCount,  tran_count as TransactionCount,last_commit_time as LastCommitTime,";
            m_sQueryScanLog += " log_record_count as LogRecordCount, schema_change_count as SchemaChangeCount,";
            m_sQueryScanLog += " command_count as CommandCount, last_commit_cdc_time LastCommitCDCTime, ";
            m_sQueryScanLog += " Latency, empty_scan_count as EmptyScanCount, failed_sessions_count as FailedSessionsCount,";
            m_sQueryScanLog += " case when duration > 0 then cast((command_count/duration) as varchar(20)) else 'NA' end AS [Throughput]";
            m_sQueryScanLog += " FROM sys.dm_cdc_log_scan_sessions order by start_time desc ";

        }

        private void Monitor_Load(object sender, EventArgs e)
        {
            try
            {
                m_sErrorMessage = String.Empty;
            }
            catch(Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool LoadCDCLogsForm()
        {
            try
            {
                m_sErrorMessage = String.Empty;
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = m_sConnectionString;

                DbCommand command = factory.CreateCommand();

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                command.Connection = connection;
                command.CommandType = CommandType.Text;
                command.CommandText = m_sQueryErrorLog;

                DataTable dtCDCErrors = new DataTable();
                DbDataAdapter adapter = factory.CreateDataAdapter();
                adapter.SelectCommand = command;
                adapter.Fill(dtCDCErrors);

                //Scan log
                

                command.Connection = connection;
                command.CommandType = CommandType.Text;
                command.CommandText = m_sQueryScanLog;

                DataTable dtCDCScanLog = new DataTable();
                adapter.SelectCommand = command;
                adapter.Fill(dtCDCScanLog);


                if (null != dtCDCErrors && dtCDCErrors.Rows.Count > 0)
                {
                    grdErrorLog.DataSource = dtCDCErrors;
                    grdErrorLog.Visible = true;
                    lblErrorStatus.Visible = false;
                }
                else
                {
                    grdErrorLog.Visible = false;
                    lblErrorStatus.Visible = true;
                }
                if (null != dtCDCScanLog && dtCDCScanLog.Rows.Count > 0)
                {
                    grdScanLog.DataSource = dtCDCScanLog;
                    grdScanLog.Visible = true;
                    lblScanLogStatus.Visible = false;
                }
                else
                {
                    grdScanLog.Visible = false;
                    lblScanLogStatus.Visible = true;
                }
                m_sErrorMessage = String.Empty;

                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private void btnRefreshErrorLog_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                m_sErrorMessage = String.Empty;
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = m_sConnectionString;

                DbCommand command = factory.CreateCommand();

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                command.Connection = connection;
                command.CommandType = CommandType.Text;
                command.CommandText = m_sQueryErrorLog;

                DataTable dtCDCErrors = new DataTable();
                DbDataAdapter adapter = factory.CreateDataAdapter();
                adapter.SelectCommand = command;
                adapter.Fill(dtCDCErrors);

                if (null != dtCDCErrors && dtCDCErrors.Rows.Count > 0)
                {
                    grdErrorLog.DataSource = dtCDCErrors;
                    grdErrorLog.Visible = true;
                    lblErrorStatus.Visible = false;
                }
                else
                {
                    grdErrorLog.Visible = false;
                    lblErrorStatus.Visible = true;
                }

                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRefreshScanLog_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                m_sErrorMessage = String.Empty;
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = m_sConnectionString;

                DbCommand command = factory.CreateCommand();

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                //Scan log
                command.Connection = connection;
                command.CommandType = CommandType.Text;
                command.CommandText = m_sQueryScanLog;

                DataTable dtCDCScanLog = new DataTable();
                DbDataAdapter adapter = factory.CreateDataAdapter();
                adapter.SelectCommand = command;
                adapter.Fill(dtCDCScanLog);


                if (null != dtCDCScanLog && dtCDCScanLog.Rows.Count > 0)
                {
                    grdScanLog.DataSource = dtCDCScanLog;
                    grdScanLog.Visible = true;
                    lblScanLogStatus.Visible = false;
                }
                else
                {
                    grdScanLog.Visible = false;
                    lblScanLogStatus.Visible = true;
                }


                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);             
            }
        }

        
    }

}
